package com.eddie.sparse;

import java.io.*;

public class Sparsearray {

    public static void main(String[] args) {
//        int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
//        for (int i = 1; i < sparseArr.length; i++) {
//            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
//        }
//        for (int[] row : chessArr2) {
//            for (int i : row) {
//                System.out.printf("%d\t", i);
//            }
//            System.out.println();
//        }
    }

    public static void saveSparseArray(int[][] arr) {
        int[][] chessArr1 = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        System.out.println("原始二维数组");
        for (int[] row : chessArr1) {
            for (int i : row) {
                System.out.printf("%d\t", i);
            }
            System.out.println();
        }
        //二维数组转为稀疏数组
        //1、先遍历，得到非0数据的个数
        int sum = 0;
        for (int[] value : chessArr1) {
            for (int i : value) {
                if (i != 0) {
                    sum++;
                }
            }
        }
        //2、创建对应的稀疏数组
        int[][] sparseArr = new int[sum + 1][3];
        //给稀疏数组赋值
        sparseArr[0][0] = chessArr1.length;
        sparseArr[0][1] = chessArr1[0].length;
        sparseArr[0][2] = sum;
        int count = 0;
        for (int i = 0; i < chessArr1.length; i++) {
            for (int j = 0; j < chessArr1[i].length; j++) {
                if (chessArr1[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }


        File faw = new File("D://sparesArr.txt");
        try {
            PrintStream printStream = new PrintStream(new FileOutputStream(faw));
            for (int[] ints : sparseArr) {
                StringBuilder str = new StringBuilder();
                for (int i = 0, intsLength = ints.length; i < intsLength; i++) {
                    int anInt = ints[i];
                    str.append(anInt);
                    if (i != ints.length - 1) {
                        str.append(",");
                    }
                }
                printStream.println(str);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
